<template>
    <div class="login-container">
    <video
      class="video"
      muted
      src="../../assets/video/lady Lex.mp4"
      loop="loop"
      autoplay="true"
    ></video>
    <el-form
      :model="loginForm"
      status-icon
      :rules="rules"
      ref="loginForm"
      label-width="100px"
      class="login-loginForm"
    >
      <h1 class="title" v-text="title"></h1>
      <i
        @click="
          isErweiLogin = !isErweiLogin;
          sms = false;
          title = '微信扫码登陆';
        "
        :class="[
          'jiaobiao',
          'iconfont',
          isErweiLogin ? 'icon-diannaojiaobiao' : 'icon-erweimajiaobiao',
        ]"
      ></i>
      <div class="common-login" v-if="!isErweiLogin">
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="loginForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="captcha">
          <el-input
            maxlength="5"
            v-model="loginForm.captcha"
            class="captcha"
            ref="captcha"
            @keydown.native.enter="submitForm('loginForm')"
          ></el-input>
          <span @click="updateCaptcha" class="captcha-svg" v-html="captchaSvg"></span>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('loginForm')">提交</el-button>
        </el-form-item>
        <!-- <el-form-item>
          <div class="sms">
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-shouji"></use>
            </svg>
            <a
              href="javascript:;"
              @click="
                sms = true;
                isErweiLogin = true;
                title = '短信登陆';
              "
              style="color: #fff; font-size: 16px"
              >切换短信登录</a
            >
          </div>
        </el-form-item> -->
      </div>

      <div class="erwei" v-else-if="!sms && isErweiLogin">
        <div class="img" v-loading="loading">
          <img :src="qrDataUrl" width="200px" alt="" />
          <i class="mask" :style="qrStyle" @click="getQrcode" v-show="isScanCodeSuccess">
          </i>
        </div>
        <p v-text="qrtip"></p>
      </div>
      <!-- <div class="smsContainer" v-else>
        <el-form-item label="手机号">
          <el-input maxlength="11" v-model="phoneNumber" class="captcha phone"></el-input>
            <span
            @click="sendSmsCode"
            class="captcha-svg"
            style="color: #888; line-height: 45px">
            >点击发送验证码
          </span>
          
        </el-form-item>
        <el-form-item label="验证码">
          <el-input v-model="smsCode"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="smsSubmit">提交</el-button>
        </el-form-item>
      </div> -->
    </el-form>
  </div>
</template>

<<script>
import * as api from "../../api";
import { mapMutations } from "vuex";
import io from "socket.io-client";
import qrcode from "qrcode";
import codeSuccessImg from "../../assets/imgs/scancode.png";
import codeInvalidImg from "@/assets/imgs/invalidQr.png";
var validateCaptcha = (rule, value, callback) => {
  if (value.length !== 5) {
    callback("验证码必须是5位");
  } else {
    callback();
  }
};
var validateUsername = (rule, value, callback) => {
  var reg = /^\w{3,12}$/;

  if (reg.test(value)) {
    callback();
  } else {
    callback("用户名可以是字母数字下划线,3-12位");
  }
};
var validatePass = (rule, value, callback) => {
  if (value.length < 3) {
    callback("密码长度不能小于3位");
  } else {
    callback();
  }
};
export default {
  data() {
    return {
      smsCode: "",
      phoneNumber:"",
      codeLoading:false,
      loading: true,
      title:"皮兰管理",
      isErweiLogin:false,
      qrtip:"请使用终端微信扫码登录",
      captchaSvg: "",
      sms:false,
      loginForm: {
        username: "",
        password: "",
        captcha: "",
      },
      rules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }],
        captcha: [{ validator: validateCaptcha, trigger: "blur" }],
      },
      qrDataUrl: "",
      isScanCodeSuccess: false,
      qrStyle: {
        backgroundImage: `url(${codeSuccessImg})`,
      },
    };
  },
  created() {
    this.updateCaptcha();
  },
  methods: {
    sendSmsCode() {
      api.getSmsCode(this.phoneNumber).then((res) =>{
        if(res.data.state) {
          this.$message.success("短信验证码发送成功");
        }else{
          this.$message.error("短信发送失败");
        }
      });
    },

    smsSubmit() {
      const loading = this.$loading({
        lock: true,
        text: "正在连接中枢,请稍后...",
        spinner: "iconfont icon-jiazaizhong",
        background: "rgba(0,0,0,0.7)",
      });
      api.loginApi(null,null,{type:"sms"}, this.smsCode).then((res) =>{
        if(res.data.state) {
          loading.close();
          this.$message.success({
            message:"连接成功,正在进行折跃。。。",
            type:"success",
            duration:1000,
          });

          localStorage.setItem("lex-token",res.data.token);
          localStorage.setItem("lex-userInfo",JSON.stringify(res.data.userInfo));
          localStorage.setItem(
            "permissionButtons",
            JSON.stringify(res.data.permission,buttons)
          );
          this.SET_USER_INFO(res.data.userInfo);
          this.$router.push("/");
        }else{
          loading.close();
        }
      });
    },
    getQrcode() {
      this.isScanCodeSuccess = false;
      this.qrStyle.backgroundImage = `url(${codeSuccessImg})`;
      let sid = localStorage.getItem("lex-sid");
      if(!sid) {
        this.$message.error("没有sid");
        return;
      }
      api.getQrcodeUrlApi(sid).then((res) =>{
        this.qrtip = "请使用终端微信扫码登录";
        let qrUrl = res.data.scanCodeUrl;
        qrcode.toDataURL(qrUrl, (err,dataUrl) =>{
          this.qrDataUrl = dataUrl;
        });
      });
    },
    ...mapMutations(["SET_USER_INFO"]),

    updateCaptcha() {
      this.codeLoading = true;
      api.getCaptchaApi().then((res) => {
        this.captchaSvg = res.data.img;
        this.codeLoading = false;
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "正在链接中枢系统...",
            spinner: "iconfont icon-jiazaizhong",
            background: "rgba(0, 0, 0, 0.7)",
          });

          api.verifyCaptcha(this.loginForm.captcha.toLowerCase()).then((res) => {
            if (res.data.state) {
              api
                .loginApi(this.loginForm.username, this.loginForm.password)
                .then((res) => {
                  if (res.data.state) {
                    loading.close();
                    this.$message.success({
                      message: "连接成功,正在进行跃迁",
                      type: "success",
                      duration: 1000,
                    });

                    localStorage.setItem("lex-token", res.data.token);

                    localStorage.setItem(
                      "lex-userInfo",
                      JSON.stringify(res.data.userInfo)
                    );

                    localStorage.setItem(
                      "permissionButtons",
                      JSON.stringify(res.data.permission.buttons)
                    );

                    this.SET_USER_INFO(res.data.userInfo);

                    this.$router.push("/");
                  } else {
                    loading.close();
                  }
                });
            } else {
              loading.close();
              this.loginForm.captcha = "";
              this.$refs.captcha.focus();
              this.updateCaptcha();
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  watch: {
    isErweiLogin(newVal, oldVal) {
      if (newVal) {
        this.loading = true;
        this.qrDataUrl = "";
        let socket = io("ws://chst.vip");

        socket.on("connectSuccess", (data) => {
          let { sid } = data;
          localStorage.setItem("lex-sid", sid);

          this.getQrcode();
        });

        socket.on("scancodeSuccess", (data) => {
          if (data.state) {
            this.isScanCodeSuccess = true;
            api.wechatLoginApi(data.wechatCode).then((res) => {
              if (res.data.state) {
                console.log(res);

                localStorage.setItem("lex-token", res.data.token);

                localStorage.setItem("lex-userInfo", JSON.stringify(res.data.userInfo));

                this.SET_USER_INFO(res.data.userInfo);

                localStorage.setItem(
                  "permissionButtons",
                  JSON.stringify(res.data.permission.buttons)
                );

                this.$router.push("/");
              } else {
                this.$message.error("微信登入失败");
              }
            });
          } else {
            this.$message.error("扫码失败");
          }
        });

        socket.on("invalidCode", (data) => {
          console.log(data);
          this.qrStyle.backgroundImage = `url(${codeInvalidImg})`;
          this.isScanCodeSuccess = true;
          this.qrtip = "二维码失效,请点击刷新二维码";
        });
      } else {
        this.isScanCodeSuccess = false;
      }
    },
  },
};
</script>

<style scoped lang="less">
.login-container {
  video {
    position: fixed;
    width: 100%;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    // height:100%;
  }
  .erwei .img {
    display: inline-block;
    position: relative;
    width: 200px;
    height: 200px;
    img {
      position: absolute;
      left: 0;
    }
    .mask {
      width: 100%;
      height: 100%;
      opacity: 0.8;
      background-color: #fff;
      position: absolute;
      left: 0;
      background-size: 50%;
      background-repeat: no-repeat;
      background-position: center;
      cursor: pointer;
    }
  }
  .jiaobiao {
    font-size: 60px;
    color: #fff;
    position: absolute;
    right: -1px;
    top: -1px;
    cursor: pointer;
    opacity: 0.7;
  }
  .el-form {
    position: fixed;
    right: 10%;
    top: 25%;
    border-radius: 5px;
    width: 400px;
    background-color: rgba(0, 0, 0, 0.3);
    padding: 100px 0 50px 0;
    /deep/ .el-input__inner {
      width: 250px;
    }
    /deep/ .el-button--primary {
      background: linear-gradient(90deg, #1596fb, #002dff);
      width: 250px;
    }
    /deep/ .el-form-item__label {
      color: #fff;
    }
    .title {
      margin: 0 0 60px 0;
      text-align: center;
      color: #01B7D2;
    }
    /deep/ .captcha {
      width: 100px;
      vertical-align: top;
      .el-input__inner {
        width: 100%;
        height: 45px;
        border-radius: 5px 0 0 5px;
        border: 0;
        font-size: 18px;
      }
    }
    svg path {
      stroke: red;
    }
    .captcha-svg {
      background: #fff;
      display: inline-block;
      height: 45px;
      width: 150px;
      text-align: center;
      cursor: pointer;
      border: 0;
      border-radius: 0px 5px 5px 0;
    }
    .el-form-item__content {
      width: 250px !important;
    }
  }
}
.sms {
  margin-left: -15px !important;
  width: 250px !important;
}

.smsContainer {
  padding-right: 20px !important;
  width: 89%;

  /deep/ .el-form-item__label {
    padding: 0 !important;
    padding-right: 10px !important;
  }

  /deep/ .phone {
    width: 140px !important;
  }

  /deep/ .captcha-svg {
    width: 115px !important;
  }

  /deep/ .el-form-item__content {
    margin: 0;
  }
}
</style>
